// UIManager.ts
import { _decorator, Component, Node, Label, Button, EventTarget } from 'cc';
import { GameEvent } from './EventType';
import { ScoreManager } from './ScoreManager';

const { ccclass, property } = _decorator;

@ccclass('UIManager')
export class UIManager extends Component {
    @property({ type: Node })
    menuPanel: Node = null!; // 主菜单

    @property({ type: Node })
    gameOverPanel: Node = null!; // 游戏结束面板

    @property({ type: Label })
    scoreLabel: Label = null!; // 分数显示

    @property({ type: Label })
    finalScoreLabel: Label = null!; // 结束界面分数

    @property({ type: Label })
    gameOverMessage: Label = null!; // 游戏结束消息

    @property({ type: ScoreManager })
    scoreManager: ScoreManager = null!;

    public static instance: UIManager;
    private eventTarget: EventTarget = new EventTarget();

    onLoad() {
        if (!UIManager.instance) UIManager.instance = this;
        else this.destroy();

        // 绑定按钮事件
        this.menuPanel.getChildByName('startBtn').getComponent(Button).node.on('click', () => {
            this.hideMenu();
            this.eventTarget.emit(GameEvent.GAME_START);
        });
        
        this.gameOverPanel.getChildByName('restartBtn').getComponent(Button).node.on('click', () => {
            this.hideGameOver();
            this.eventTarget.emit(GameEvent.GAME_RESTART);
        });

        // 监听分数变化
        if (this.scoreManager) {
            this.scoreManager.getEventTarget().on(GameEvent.SCORE_CHANGE, (score: number) => {
                this.scoreLabel.string = `分数: ${score}`;
            }, this);
        }
    }

    start() {
        this.hideGameOver();
    }

    // 显示游戏结束界面
    showGameOver(score: number) {
        this.gameOverPanel.active = true;
        this.finalScoreLabel.string = `Final Score: ${score}`;
        this.gameOverMessage.string = score === 0 ? "Game Over - Reached Center!" : "Game Over!";
    }

    // 隐藏游戏结束界面
    hideGameOver() {
        this.gameOverPanel.active = false;
    }

    // 隐藏主菜单
    hideMenu() {
        this.menuPanel.active = false;
    }

    /** 获取事件目标 */
    public getEventTarget(): EventTarget {
        return this.eventTarget;
    }

    onDestroy() {
        UIManager.instance = null!;
        this.eventTarget.targetOff(this);
        if (this.scoreManager) {
            this.scoreManager.getEventTarget().off(GameEvent.SCORE_CHANGE, null, this);
        }
    }
}
